package streaming.test.file;

import java.io.IOException;

import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.ConfigureCompleteEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.DataSink;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoDataSinkException;
import javax.media.NoDataSourceException;
import javax.media.NoProcessorException;
import javax.media.NotConfiguredError;
import javax.media.NotRealizedError;
import javax.media.Processor;
import javax.media.RealizeCompleteEvent;
import javax.media.format.AudioFormat;
import javax.media.protocol.FileTypeDescriptor;

// works

/** 
 * 	Snimanje zvuka u fajl:
 * 
 * Naci adekvatni capturing device upotrebom CaptureDeviceManagera. Kreirati procesor 
 * od lokatora za taj device. Napraviti DataSink pomocu DataSoure-a procesora, pozivajuci
 * getDataOutput metodu. Bitno je prije proslijedjivanja dataSource-a sinku, specificirati
 * contentDescriptor za procesor. otvoriti sink, startovati sink, startovati procesor.
 * 
 * 
 */

public class FileRecorder implements ControllerListener{

	private Processor processor;
	private DataSink dataSink;
	private CaptureDeviceInfo selectedDevice;
	private String url = "file://test.wav";
	private AudioFormat format = new AudioFormat(AudioFormat.LINEAR);
	
	public FileRecorder() throws Exception{
		capture();
	
	}

	private synchronized void capture() throws IOException, NoProcessorException,
			NoDataSourceException, InterruptedException, NotConfiguredError,
			NotRealizedError {
		selectedDevice = (CaptureDeviceInfo) CaptureDeviceManager.getDeviceList(format).get(0);
		
		processor = Manager.createProcessor(Manager.createDataSource(selectedDevice.getLocator()));
		processor.addControllerListener(this);
		processor.configure();
		wait();
		System.out.println("processor configured");
		processor.setContentDescriptor(new FileTypeDescriptor(FileTypeDescriptor.WAVE));
		processor.realize();
		wait();
		try {
			dataSink = Manager.createDataSink(processor.getDataOutput(), new MediaLocator(url));
		
			dataSink.open();
			dataSink.start();
			processor.start();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Thread.sleep(5000);
		processor.close();
		dataSink.close();
	}
	
	@Override
	public synchronized void controllerUpdate(ControllerEvent e) {

		if(e instanceof ConfigureCompleteEvent){
			notifyAll();
		}
		else if(e instanceof RealizeCompleteEvent){
			notifyAll();
		}
		
		
	}
	
	
	public static void main(String[] args) {
		try {
			new FileRecorder();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
}
